package nl.dxn.tunnel.client.handel;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import nl.dxn.tunnel.client.Constants;
import nl.dxn.tunnel.client.executors.AuthExecutor;
import nl.dxn.tunnel.enums.TransferMessageType;
import nl.dxn.tunnel.po.MessageConfig;
import nl.dxn.tunnel.po.TransferMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

public class HttpClientHandel extends SimpleChannelInboundHandler<byte[]> {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientHandel.class);
    private final MessageConfig config;

    public HttpClientHandel(MessageConfig config) {
        this.config = config;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] bytes) throws Exception {
        try {
            Channel proxyChannel = ctx.channel().attr(Constants.PROXY).get();
            if (Objects.isNull(proxyChannel)) {
                ctx.close();
                return;
            }

            //logger.info("{}",new String(bytes,"utf-8"));

            TransferMessage message = new TransferMessage();
            message.setData(bytes);
            message.setConfig(config);
            message.setType(TransferMessageType.TYPE_DATA);
            proxyChannel.writeAndFlush(message);
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    /**
     * 连接中断
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            logger.info("agent {} {} {} 连接中断",config.getServerId(),config.getChannelId(),ctx.channel().remoteAddress());
            Channel proxy = ctx.channel().attr(Constants.PROXY).get();
            if (proxy == null) {
                ctx.close();
                return;
            }

            TransferMessage sendMessage = new TransferMessage();
            sendMessage.setType(TransferMessageType.TYPE_DISCONNECTED);
            sendMessage.setConfig(config);

            AuthExecutor.disConnectFromAgent(proxy,ctx.channel());

            proxy.writeAndFlush(sendMessage);
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    /**
     * 连接异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("",cause);
        ctx.close();
    }
}
